import os, re, json, urllib2, time, eyeD3, shutil

def setup():
	if not os.path.exists("db"): os.mkdir("db")
	if not os.path.exists("temp"): os.mkdir("temp")
	if not os.path.exists("db/mixcloud_db.py"):
		open("db/mixcloud_db.py", "w").write("{}")

def getIeMixcloudHistory():
	os.system('iehv\\iehv.exe /stab temp\\iehv_temp.txt /sort "~Modified Date"')
	iehv_file = open("temp/iehv_temp.txt")
	for line in iehv_file:
		url = line.split("\t")[0]
		if url.find("mixcloud.com") > 0 and url.find("player") > 0: yield url

def listDir(dir, filter = ""):
	pattern = re.compile(filter)
	filenames = {}
	for filename in os.listdir(dir):
		if pattern.match(filename):
			filenames[filename] = dir+"/"+filename
	return filenames

def getDbByFilename(db):
	db_by_filename = {}
	for url, data in db.iteritems():
		if "mp3_urls" not in data: continue
		mp3_url = data["mp3_urls"][0].lower()
		mp3_filename = re.sub(".*/(.*?mp3)", "\\1", mp3_url, re.IGNORECASE)
		db_by_filename[mp3_filename] = data
	return db_by_filename

def getComment(data):
	comments = []
	genres = []
	for genre in data["genres"]:
		genres.append(genre["title"])
	comments.append(u", ".join(genres))
	comments.append("")
	for section in data["sections"]:
		if not section["track"]: continue
		song = u"%s - %s" % (section["track"]["artist"]["name"], section["track"]["song"]["name"])
		comments.append(song.replace("["," ").replace("]", " "))
	return u"\n".join(comments)

def coverImage(data):
	tempfile_path = "temp/%s.jpg" % data["id"]
	if not os.path.exists(tempfile_path):
		local_image = open(tempfile_path, "wb", 10240)
		remote_image = urllib2.urlopen(data["picture_url"])
		shutil.copyfileobj(remote_image, local_image) 
	return tempfile_path

def updateInfos(files, db, genre):
	db_by_filename = getDbByFilename(db)
	print " * Updating file Infos (%s files, genre: %s)..." % (len(files), genre)
	for filename, filepath in files.iteritems():
		print " -",filename,
		old_filename = filename
		filename = filename.replace("[1]", "").replace("[2]","").replace("[3]", "").replace(".mpeg", ".mp3").lower()
		if filename in db_by_filename:
			print "Found, Updating...",
		else:
			print "Not found, Skipping."
			continue
		data = db_by_filename[filename]
		tag = eyeD3.Tag()
		tag.setVersion((2,3,0))
		tag.setTextEncoding(eyeD3.UTF_16_ENCODING)
		tag.link(filepath)
		tag.setArtist(u"Mixcloud")
		tag.setAlbum(genre)
		tag.setTitle(data["name"]+" - "+data["display_name"])
		tag.setURLFrame("WPUB", data["cloudcast_url"].encode("latin2"))
		#tag.removeComments()
		#tag.addComment(getComment(data))
		tag.removeLyrics()
		tag.addLyrics(getComment(data))
		tag.removeImages()
		tag.addImage(3, coverImage(data))
		tag.setVersion((2,3,0))
		tag.update()
		print "Updated."
		new_filepath = filepath.replace(old_filename, filename)
		if new_filepath != filepath:
			os.rename(filepath, new_filepath)

def getMixcloudJson(url):
	json_url = url.replace("http://www.mixcloud.com", "http://www.mixcloud.com/api/1/cloudcast")
	json_url = re.sub("/player$", "", json_url)
	json_url = json_url+".json?embed_type=website_unknown"
	data = urllib2.urlopen(json_url).read()
	return json.loads(data)

def updateDb():
	print " * Loading db..."
	db = json.load(open("db/mixcloud_db.py"))
	print " * Checking new urls..."
	for url in getIeMixcloudHistory():
		if url not in db:
			print " - New url:", url
			db[url] = getMixcloudJson(url)
			time.sleep(1)
	print " * Saving new db..."
	json.dump(db, open("db/mixcloud_db.py", "w"), indent=4)
	return db

setup()
db = updateDb()
#files = listDir(r"s:\Mp3\__mixcloud__\Hip-Hop", ".*\[1\].*mpeg")
updateInfos(listDir(r"s:\Mp3\__mixcloud__\Hip-Hop", ".*mpeg"), db, u"Hip-Hop")
updateInfos(listDir(r"s:\Mp3\__mixcloud__\Dance", ".*mpeg"), db, u"Dance")
updateInfos(listDir(r"s:\Mp3\__mixcloud__\Electro", ".*mpeg"), db, u"Electro")
updateInfos(listDir(r"s:\Mp3\__mixcloud__\Chill", ".*mpeg"), db, u"Chill")